package com.ruoyi.web.controller.shaketicket;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.jiugongge.domain.Jiugongge;
import com.ruoyi.jiugongge.domain.JiugonggePrizes;
import com.ruoyi.jiugongge.domain.JiugonggeRecord;
import com.ruoyi.jiugongge.domain.JiugonggeRegistration;
import com.ruoyi.jiugongge.domain.WeixinDto;
import com.ruoyi.jiugongge.mapper.JiugonggePrizesMapper;
import com.ruoyi.jiugongge.mapper.JiugonggeRegistrationMapper;
import com.ruoyi.jiugongge.service.IJiugonggePrizesService;
import com.ruoyi.jiugongge.service.IJiugonggeRecordService;
import com.ruoyi.jiugongge.service.IJiugonggeService;
import com.ruoyi.shaketicket.domain.ShaketicketAward;
import com.ruoyi.shaketicket.domain.ShaketicketHome;
import com.ruoyi.shaketicket.domain.ShaketicketRecord;
import com.ruoyi.shaketicket.service.IShaketicketAwardService;
import com.ruoyi.shaketicket.service.IShaketicketHomeService;
import com.ruoyi.shaketicket.service.IShaketicketRecordService;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.common.utils.AjaxJson;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LotteryUtil;
import com.ruoyi.common.utils.RandomUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDUtil;
import com.ruoyi.common.utils.WeiXinHttpUtil;

/**
 * 摇一摇活动 信息操作处理
 * 
 * @author lzy
 * @date 2019年3月1日
 */
@Controller
@RequestMapping("/shaketicket")
public class ShaketicketIndexController extends BaseController {

	@Autowired
	private IShaketicketHomeService homeService;
	@Autowired
	private IShaketicketRecordService recordService;
	@Autowired
	private IShaketicketAwardService awardService;

	protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(ShaketicketIndexController.class);

	/**
	 * @throws Exception
	 * @功能 测试地址
	 * @时间 2019年3月1日
	 */
	@GetMapping("/index")
	public void index(String code, HttpServletRequest request, HttpServletResponse response) throws Exception {


		response.sendRedirect("/jiugongge/toIndex?jwid=WEQ");

	}

	@GetMapping("/toIndexx")
	@ResponseBody
	public String toIndexx(String openId) {

		return "";

	}

	
	/**
	 * @功能   跳转到活动首页  
	 * @时间 2019年3月1日 
	 */
	@RequestMapping(value = "/toIndex", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String toIndex(@ModelAttribute WeixinDto weixinDto,
			HttpServletRequest request, HttpServletResponse response,Model model)
			throws Exception {
		logger.info("---------------摇一摇跳转活动首页开始---------------------------");
		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getAppid();
		String actId = weixinDto.getActId();
		String openid = weixinDto.getOpenid();
		
		String nickname = URLDecoder.decode(weixinDto.getNickname(), "UTF-8");
	    weixinDto.setNickname(nickname);
	    
	   /* logger.info("---------------跳转活动首页昵称---------------------------" + nickname);*/
		
		
		// 调试
	  /*weixinDto.setNickname("lzydemo"); weixinDto.setHeadimgurl(
	  "https://micromart.oss-cn-beijing.aliyuncs.com/timg.jpg");*/
	  
		
		
		try {	
			// 获取活动信息
			ShaketicketHome shaketicket = homeService.selectShaketicketHomeById(actId);
			
			model.addAttribute("shaketicket", shaketicket);
			
			// 参数验证
			String validateWeixinDtoParam = validateWeixinDtoParam(weixinDto);

			if (validateWeixinDtoParam.equals("success") == false) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", validateWeixinDtoParam);
				return "shaketicket/error";
			}

		
			
		   //判断活动是否开始结束
		   /*String validateActDate = validateActDate(shaketicket);
			
			if(validateActDate != null){
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", validateActDate);
				return "shaketicket/error";
			}*/
			
			if (!jwid.equals(shaketicket.getJwid())) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", "活动不属于该微信公众号");
				return "shaketicket/error";
			}			
			if("0".equals(shaketicket.getActiveFlag())){
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", "活动未激活！");
				return "shaketicket/error";
			}
			
			//模版简称
			/*if (StringUtils.isNotEmpty(shaketicket.getTemplate())) {
				viewName = "shaketicket/"+shaketicket.getTemplate()+"/vm/index.vm";
			}*/
			
			//每天次数设置为0，代表不限制每天抽奖次数
			if(shaketicket.getNumPerDay()==0){
				model.addAttribute("perday", 0);
			}
			Date currDate = new Date();
			// 根据活动id，访问人openid查询抽奖人抽奖次数和每日抽奖次数
			Map<String, Integer> countMap = recordService
					.getRecordCountByActIdAndOpenid(actId,openid, currDate);
			model.addAttribute("weixinDto", weixinDto);
			int count= ((Number)countMap.get("count")).intValue();
			int countday= ((Number)countMap.get("countday")).intValue();
			model.addAttribute("count", count);//累计抽奖次数
			model.addAttribute("countday", countday);//每日抽奖次数
			
			String url = request.getRequestURL() + "?"
					+ request.getQueryString();
			if (url.indexOf("#") != -1) {
				url = url.substring(0, url.indexOf("#"));
			}
			
			//是否关注可参加
			/*if("1".equals(shaketicket.getFoucsUserCanJoin())){
				String qrcodeUrl = baseApiJwidService.getQrcodeUrl(weixinDto.getJwid());
				velocityContext.put("qrcodeUrl", qrcodeUrl);
			}*/
			
			System.out.println("--------------当前访问PageUrl---------------："
					+ url);
			model.addAttribute("nonceStr", WeiXinHttpUtil.nonceStr);
			model.addAttribute("timestamp", WeiXinHttpUtil.timestamp);
			model.addAttribute("hdUrl", shaketicket.getHdurl());
			model.addAttribute("appId", appid);
			model.addAttribute("signature",WeiXinHttpUtil.getRedisSignature(request, jwid));
			//底部logo修改
			model.addAttribute("huodong_bottom_copyright", "lzy");
		
		} catch (Exception e) {
			logger.info("------------出错了-----------"+ e.getMessage());

		}
		return "shaketicket/shaketicket";
	}
	
	
	

	/**
	 * @功能 摇奖  
	 * @时间 2019年3月4日 
	 */
	@RequestMapping(value = "/shakeTicket", method = { RequestMethod.GET,
			RequestMethod.POST })
	@ResponseBody
	public AjaxJson shakeTicket(@ModelAttribute WeixinDto weixinDto,
			HttpServletRequest request,Model model) {
		AjaxJson j = new AjaxJson();
		
		logger.info("----------------摇奖开始----------------------");
	    
		// 装载微信所需参数
		String jwid = weixinDto.getJwid();
		String appid = weixinDto.getAppid();
		String actId = weixinDto.getActId();
		try {

			// 参数验证
			String validateWeixinDtoParam = validateWeixinDtoParam(weixinDto);
			if (validateWeixinDtoParam.equals("success") == false) {
				model.addAttribute("errCode", false);
				model.addAttribute("errMsg", validateWeixinDtoParam);
				j.setSuccess(false);
				j.setMsg(validateWeixinDtoParam);
				logger.info("--------------------微信所需参数错误---------------");
			}

		/*	if (weixinDto.getOpenid() != null) {
				String nickname = WeiXinHttpUtil.getNickName(
						weixinDto.getOpenid(), jwid);
				weixinDto.setNickname(EmojiFilter.filterEmoji(nickname));
			}*/
			
			// 获取活动信息
			ShaketicketHome shaketicket = homeService.selectShaketicketHomeById(weixinDto.getActId());
			
			//是否关注可参加
			weixinDto.setSubscribe("0");
			setWeixinDto(weixinDto);
			if("1".equals(shaketicket.getFoucsUserCanJoin())){//如果活动设置了需要关注用户才能参加	
				//未关注
				 if(!"1".equals(weixinDto.getSubscribe())){
					 j.setSuccess(false);
					 j.setObj("isNotFoucs");
					 return j;
				 }
			 }
			
			//是否关注可参加---------------			
		    /*if("1".equals(shaketicket.getBindingMobileCanJoin())){//如果活动设置了需要绑定手机号才能参加				
				// 获取绑定手机号
				String bindPhone = getBindPhone(weixinDto.getOpenid(),jwid);
				// 判断是否绑定了手机号
				if (StringUtils.isEmpty(bindPhone)) {
					j.setSuccess(false);
					j.setObj("isNotBind");
					return j;
				}
			}*/
			Date currDate = new Date();
			// 根据活动id，访问人openid查询抽奖人抽奖次数和每日抽奖次数
			Map<String, Integer> countMap = recordService
					.getRecordCountByActIdAndOpenid(weixinDto.getActId(),weixinDto.getOpenid(), currDate);	
			int count= ((Number)countMap.get("count")).intValue();
			int countday= ((Number)countMap.get("countday")).intValue();
			int wincount= ((Number)countMap.get("wincount")).intValue();
			// 判断总抽奖次数是否用完
			if (shaketicket.getCount()!=null&&shaketicket.getCount()!=0&&count>= shaketicket.getCount()) {
				j.setSuccess(false);
				j.setMsg("总抽奖次数已用完");
				logger.info("---------------总抽奖次数已用完------------------");
			}
			if(shaketicket.getNumPerDay()!= 0){	//每天次数设置为0，代表不限制每天抽奖次数，如果不等于0代表限制了每天抽奖次数	
				if (countday>= shaketicket.getNumPerDay()) {
				j.setSuccess(false);
				j.setMsg("今日抽奖次数已用完");
				logger.info("---------------今日抽奖次数已用完------------------");
				}
			}
			//生成用户的抽奖记录
			ShaketicketRecord shaketicketRecord = new ShaketicketRecord();
			shaketicketRecord.setDrawStatus("0");//初始化为未中奖
			//为用户抽取活动奖品
			//得到有剩余的活动奖品
			List<ShaketicketAward> awards = awardService.queryRemainAwardsByActId(weixinDto.getActId());
			if("0".equals(shaketicket.getWinCanJoin())){//活动设置为中奖可继续参与	
				//得到各奖品的概率列表
				List<Double> orignalRates = new ArrayList<Double>(awards.size());
				for (ShaketicketAward award : awards) {
					orignalRates.add(award.getProbability());
				}
				//根据概率产生奖品
				int index = LotteryUtil.lottery(orignalRates);					
				if (index>=0) {//中奖啦
					ShaketicketAward award	= awards.get(index);
					shaketicketRecord.setAwardId(award.getId());
					shaketicketRecord.setDrawStatus("1");//设置为已中奖
				}
			}else{//活动设置为中奖不可继续参与，即一旦中奖不可继续参与	
				if (wincount==0) {//中将次数为0，表示没有中过奖。可继续正常参与抽奖
					//得到各奖品的概率列表
					List<Double> orignalRates = new ArrayList<Double>(awards.size());
					for (ShaketicketAward award : awards) {
						orignalRates.add(award.getProbability());
					}
					//根据概率产生奖品
					int index = LotteryUtil.lottery(orignalRates);					
					if (index>=0) {//中奖啦
						ShaketicketAward award	= awards.get(index);
						shaketicketRecord.setAwardId(award.getId());
						shaketicketRecord.setDrawStatus("1");//设置为已中奖
					}
				}else{
					j.setSuccess(false);
					j.setMsg("抽奖失败!");
					logger.info("-------------抽奖失败-------------"); 
				}
			}
			ShaketicketAward award = recordService.creatRecordAndReturnAward(shaketicketRecord,weixinDto);
			j.setSuccess(true);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("shaketicketRecord",shaketicketRecord);
			map.put("shaketicketAward",award);
			j.setAttributes(map);	
		} catch (Exception e) {
			e.printStackTrace();
			j.setSuccess(false);
			j.setMsg("抽奖失败!");
		}
		return j;
	}
	
	
	


	private String validateWeixinDtoParam(WeixinDto weixinDto) {
		if (StringUtils.isEmpty(weixinDto.getActId())) {

			return "活动ID不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getOpenid())) {

			return "参与人openid不能为空";
		}
		if (StringUtils.isEmpty(weixinDto.getJwid())) {

			return "微信ID不能为空";
		}
		return "success";
	}

	

	/**
	 * 微信获取个人信息util
	 * 
	 * @param weixinDto
	 * @return 获取头像 Map两个键headimgurl,fxheadimgurl
	 */
	private Map<String, String> setWeixinDto(WeixinDto weixinDto) {
		logger.info("setWeixinDto parameter weixinDto={}", new Object[] { weixinDto });
		Map<String, String> map = new HashMap<String, String>();
		try {
			if (weixinDto.getOpenid() != null) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto Openid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("subscribe")) {
					weixinDto.setSubscribe(jsonObj.getString("subscribe"));
				} else {
					weixinDto.setSubscribe("0");
				}
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("headimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
			if (StringUtils.isNotEmpty(weixinDto.getFxOpenid())) {
				JSONObject jsonObj = WeiXinHttpUtil.getGzUserInfo(weixinDto.getFxOpenid(), weixinDto.getJwid());
				logger.info("setWeixinDto FxOpenid getGzUserInfo jsonObj={}", new Object[] { jsonObj });
				if (jsonObj != null && jsonObj.containsKey("nickname")) {
					weixinDto.setFxNickname(jsonObj.getString("nickname"));
				} else {
					weixinDto.setFxNickname("");
				}
				if (jsonObj != null && jsonObj.containsKey("headimgurl")) {
					map.put("fxheadimgurl", jsonObj.getString("headimgurl"));
				} else {
					map.put("fxheadimgurl", "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("setWeixinDto e={}", new Object[] { e });
		}
		return map;
	}

	/**
	 * @功能：随机生成兑奖码
	 * @return
	 */
	private synchronized static String getCoupon() {
		char ch[] = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
				'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
				'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
				'X', 'Y', 'Z' };
		Random rand = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 20; i++) {
			sb.append(ch[rand.nextInt(62)]);
		}
		return sb.toString();
	}

	
	private String validateActDate(ShaketicketHome shaketicket) {
		Date date = new Date();
		if (shaketicket == null) {
			/*throw new ShaketicketHomeException(
					ShaketicketHomeExceptionEnum.DATA_NOT_EXIST_ERROR, "活动不存在");*/
			return "活动不存在";
		}
		if(shaketicket.getBeginTime()!=null){
			if (date.before(shaketicket.getBeginTime())) {
				/*throw new ShaketicketHomeException(
						ShaketicketHomeExceptionEnum.ACT_BARGAIN_NO_START, "活动未开始");*/
				return "活动未开始";
			}
		}
		if(shaketicket.getEndTime()!=null){
			if (date.after(shaketicket.getEndTime())) {
				/*throw new ShaketicketHomeException(ShaketicketHomeExceptionEnum.ACT_BARGAIN_END,
						"活动已结束");*/
				return "活动已结束";
			}
		}
		return null;
	}
	
}
